/**
 * 预约挂号页面脚本
 */

// 后端API地址
const API_URL = {
    getDoctors: '/api/doctors', // 获取医生列表
    getAvailableTimes: '/api/available-times', // 获取可用时间
    createAppointment: '/user/appointment' // 创建预约
};

// 全局状态
const state = {
    selectedDepartment: '',
    selectedDate: '',
    selectedTime: '',
    selectedDoctor: null,
    doctors: [], // 医生列表
    userId: null // 当前登录用户ID
};

// DOM元素
const departmentItems = document.querySelectorAll('.department-item');
const dateScroll = document.getElementById('dateScroll');
const timeItems = document.querySelectorAll('.time-item');
const doctorList = document.getElementById('doctorList');
const loadingSpinner = document.getElementById('loadingSpinner');
const appointmentModal = document.getElementById('appointmentModal');
const appointmentForm = document.getElementById('appointmentForm');
const modalDoctorName = document.getElementById('modalDoctorName');
const modalDepartment = document.getElementById('modalDepartment');
const modalDate = document.getElementById('modalDate');
const modalTime = document.getElementById('modalTime');
const doctorIdInput = document.getElementById('doctorId');
const appointmentDateInput = document.getElementById('appointmentDate');
const appointmentTimeInput = document.getElementById('appointmentTime');
const symptomsInput = document.getElementById('symptoms');
const closeModalBtn = document.getElementById('closeModal');
const cancelBtn = document.getElementById('cancelBtn');
const submitBtn = document.getElementById('submitBtn');
const toast = document.getElementById('toast');

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 生成日期选择项
    generateDateOptions();
    
    // 初始化事件监听
    initEventListeners();
});

// 生成日期选择项
function generateDateOptions() {
    const today = new Date();
    dateScroll.innerHTML = '';
    
    // 生成未来7天的日期选项
    for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        
        const dateItem = document.createElement('div');
        dateItem.className = 'date-item' + (i === 0 ? ' active' : '');
        
        const dayLabel = document.createElement('span');
        dayLabel.className = 'day';
        dayLabel.textContent = i === 0 ? '今天' : 
                               i === 1 ? '明天' : 
                               getWeekdayName(date.getDay());
        
        const dateLabel = document.createElement('span');
        dateLabel.className = 'date';
        dateLabel.textContent = formatDate(date, 'MM/DD');
        
        // 将日期对象保存为自定义属性
        dateItem.dataset.fullDate = formatDate(date, 'YYYY-MM-DD');
        
        dateItem.appendChild(dayLabel);
        dateItem.appendChild(dateLabel);
        dateScroll.appendChild(dateItem);
        
        // 添加点击事件
        dateItem.addEventListener('click', function() {
            document.querySelectorAll('.date-item').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
            state.selectedDate = this.dataset.fullDate;
            updateDoctorList();
        });
    }
    
    // 设置初始选中日期
    state.selectedDate = document.querySelector('.date-item.active').dataset.fullDate;
}

// 初始化事件监听
function initEventListeners() {
    // 科室选择
    departmentItems.forEach(item => {
        item.addEventListener('click', function() {
            departmentItems.forEach(dept => {
                dept.classList.remove('active');
            });
            this.classList.add('active');
            state.selectedDepartment = this.dataset.department;
            updateDoctorList();
        });
    });
    
    // 时间段选择
    timeItems.forEach(item => {
        item.addEventListener('click', function() {
            if (this.classList.contains('disabled')) return;
            
            timeItems.forEach(time => {
                time.classList.remove('active');
            });
            this.classList.add('active');
            state.selectedTime = this.dataset.time;
            updateDoctorList();
        });
    });
    
    // 弹窗关闭按钮
    closeModalBtn.addEventListener('click', () => {
        appointmentModal.classList.remove('show');
    });
    
    // 取消按钮
    cancelBtn.addEventListener('click', () => {
        appointmentModal.classList.remove('show');
    });
    
    // 表单提交
    appointmentForm.addEventListener('submit', handleAppointmentSubmit);
    
    // 初始设置
    state.selectedDepartment = departmentItems[0].dataset.department;
    departmentItems[0].classList.add('active');
    state.selectedTime = timeItems[0].dataset.time;
    timeItems[0].classList.add('active');
    
    // 初始加载医生列表
    updateDoctorList();
}

// 更新医生列表
function updateDoctorList() {
    loadingSpinner.style.display = 'flex';
    doctorList.innerHTML = '';
    doctorList.appendChild(loadingSpinner);
    
    // 发送请求获取医生列表
    fetchDoctors()
        .then(doctors => {
            state.doctors = doctors;
            renderDoctorList(doctors);
        })
        .catch(error => {
            // 处理API响应错误
            if (error.message === 'unauthorized') {
                window.location.href = '../login.html'; // 交由后端进行重定向
            } else {
                showToast('获取医生列表失败，请重试');
                console.error('Error fetching doctors:', error);
                loadingSpinner.style.display = 'none';
            }
        });
}

// 获取医生列表
function fetchDoctors() {
    // 构建请求参数
    const params = new URLSearchParams({
        department: state.selectedDepartment,
        date: state.selectedDate,
        time: state.selectedTime
    });
    
    // 发送AJAX请求到后端API
    return fetch(`${API_URL.getDoctors}?${params}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include' // 包含cookies等凭证，让后端处理鉴权
    })
    .then(response => {
        if (!response.ok) {
            if (response.status === 401 || response.status === 403) {
                throw new Error('unauthorized');
            }
            throw new Error('网络响应异常');
        }
        return response.json();
    })
    .then(result => {
        // 处理返回的R<T>格式数据
        if (result.code === 1 && result.data) {
            return result.data;
        } else {
            // 如果后端返回错误
            throw new Error(result.msg || '获取医生列表失败');
        }
    })
    .catch(error => {
        console.error('Failed to fetch doctors:', error);
        throw error; // 将错误传递给调用者处理
    });
}

// 渲染医生列表
function renderDoctorList(doctors) {
    loadingSpinner.style.display = 'none';
    doctorList.innerHTML = '';
    
    if (doctors.length === 0) {
        const noResult = document.createElement('div');
        noResult.className = 'no-result';
        noResult.innerHTML = '<i class="fas fa-info-circle"></i><span>没有找到符合条件的医生</span>';
        doctorList.appendChild(noResult);
        return;
    }
    
    doctors.forEach(doctor => {
        const doctorItem = document.createElement('div');
        doctorItem.className = 'doctor-item';
        
        const specialties = doctor.specialty ? doctor.specialty.split(',') : [];
        const specialtyTags = specialties.map(specialty => 
            `<span class="tag">${specialty}</span>`
        ).join('');
        
        doctorItem.innerHTML = `
            <img src="${doctor.avatar_url || 'https://picsum.photos/100/100'}" alt="${doctor.name}头像" class="doctor-avatar">
            <div class="doctor-info">
                <h4>${doctor.name}</h4>
                <p>${doctor.title} | ${doctor.department}</p>
                <div class="tags">
                    ${specialtyTags}
                </div>
            </div>
            <button class="book-btn" data-doctor-id="${doctor.doctor_id}">预约</button>
        `;
        
        doctorList.appendChild(doctorItem);
        
        // 添加预约按钮点击事件
        const bookBtn = doctorItem.querySelector('.book-btn');
        bookBtn.addEventListener('click', () => {
            const selectedDoctor = doctors.find(d => d.doctor_id == doctor.doctor_id);
            showAppointmentModal(selectedDoctor);
        });
    });
}

// 显示预约弹窗
function showAppointmentModal(doctor) {
    state.selectedDoctor = doctor;
    
    // 填充弹窗内容
    modalDoctorName.textContent = doctor.name;
    modalDepartment.textContent = `${doctor.department}（${doctor.title}）`;
    modalDate.textContent = formatDateForDisplay(state.selectedDate);
    modalTime.textContent = state.selectedTime;
    
    // 设置隐藏字段
    doctorIdInput.value = doctor.doctor_id;
    appointmentDateInput.value = state.selectedDate;
    appointmentTimeInput.value = state.selectedTime;
    
    // 显示弹窗
    appointmentModal.classList.add('show');
}

// 处理预约表单提交
function handleAppointmentSubmit(event) {
    event.preventDefault();
    
    const symptoms = symptomsInput.value.trim();
    
    if (!symptoms) {
        showToast('请简要描述您的症状');
        return;
    }
    
    // 禁用提交按钮防止重复提交
    submitBtn.disabled = true;
    submitBtn.textContent = '预约中...';
    
    // 准备预约数据
    const appointmentData = {
        doctor_id: parseInt(doctorIdInput.value),
        appointment_date: appointmentDateInput.value,
        appointment_time: appointmentTimeInput.value,
        symptoms: symptoms
    };
    
    // 创建预约
    createAppointment(appointmentData)
        .then(result => {
            if (result.success) {
                showToast('预约成功！我们会通过短信通知您');
                appointmentModal.classList.remove('show');
                // 重置表单
                symptomsInput.value = '';
            } else {
                showToast(result.message || '预约失败，请稍后再试');
            }
        })
        .catch(error => {
            // 处理API响应错误
            if (error.message === 'unauthorized') {
                window.location.href = '../login.html'; // 交由后端进行重定向
            } else {
                showToast('预约失败，请检查网络连接');
                console.error('Error creating appointment:', error);
            }
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.textContent = '确认预约';
        });
}

// 创建预约
function createAppointment(appointmentData) {
    // 发送AJAX请求到后端API
    return fetch(API_URL.createAppointment, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include', // 包含cookies等凭证，让后端处理鉴权
        body: JSON.stringify(appointmentData)
    })
    .then(response => {
        if (!response.ok) {
            if (response.status === 401 || response.status === 403) {
                throw new Error('unauthorized');
            }
            throw new Error('网络响应异常');
        }
        return response.json();
    })
    .then(result => {
        // 处理返回的R<T>格式数据
        if (result.code === 1) {
            return {
                success: true,
                data: result.data
            };
        } else {
            return {
                success: false,
                message: result.msg
            };
        }
    });
}

// 显示提示消息
function showToast(message) {
    toast.textContent = message;
    toast.classList.add('show');
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 工具函数：获取星期几名称
function getWeekdayName(day) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weekdays[day];
}

// 工具函数：格式化日期
function formatDate(date, format) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    if (format === 'YYYY-MM-DD') {
        return `${year}-${month}-${day}`;
    } else if (format === 'MM/DD') {
        return `${month}/${day}`;
    }
    
    return `${year}-${month}-${day}`;
}

// 工具函数：格式化显示日期
function formatDateForDisplay(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekday = getWeekdayName(date.getDay());
    
    return `${year}年${month}月${day}日 ${weekday}`;
}

// 添加页面切换动画
document.addEventListener('DOMContentLoaded', () => {
    document.body.style.opacity = '0';
    setTimeout(() => {
        document.body.style.opacity = '1';
    }, 100);
});

// 返回按钮添加过渡动画
document.querySelector('.back-btn').addEventListener('click', function(e) {
    e.preventDefault();
    document.body.style.opacity = '0';
    setTimeout(() => {
        window.location.href = '../index.html';
    }, 300);
}); 